package com.enzoism.springboot.dive.bis.arraylist;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
/**
 * 参考网址：https://mp.weixin.qq.com/s/GQgerZ79qKYukodqRKUo1g
 * 自己先想想一下，创建一个有序的Vector，如何实现？
 *
 * 【核心方法】
 * 1）add(E element)
 * 2）add(int index, E element)
 * 3）get()
 * 4）remove()
 * 5）remove(Object o)
 *
 * 【构造方法】
 * 1）VectorSimple()
 * 2）VectorSimple(int initialCapacity)
 * 3）VectorSimple(Collection<? extends E> c)
 */
public class VectorSimple<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable {
    // 数组元素
    protected Object[] elementData;
    // 元素个数
    protected int size;
    // 增长因子
    protected int capacityIncrement;

    //*********************构造方法*********************//
    public VectorSimple(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

    public VectorSimple(int initialCapacity) {
        this(initialCapacity, 0);
    }

    public VectorSimple() {
        this(10);
    }

    public VectorSimple(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    }

    //*********************操作方法*********************//
    // 添加元素
    public synchronized boolean add(E e) {
        modCount++;
        ensureCapacityHelper(size + 1);
        elementData[size++] = e;
        return true;
    }
    // 添加元素
    public void add(int index, E element) {
        insertElementAt(element, index);
    }
    // 获取元素
    public synchronized E get(int index) {
        if (index >= size)
            throw new ArrayIndexOutOfBoundsException(index);

        return elementData(index);
    }

    // 删除指定元素
    public boolean remove(Object o) {
        return removeElement(o);
    }



    // 删除指定元素
    public synchronized E remove(int index) {
        modCount++;
        if (index >= size)
            throw new ArrayIndexOutOfBoundsException(index);
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                    numMoved);
        elementData[--size] = null; // Let gc do its work

        return oldValue;
    }
    // 容量扩容
    private void ensureCapacityHelper(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    // 要分配的数组的最大大小
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    // 数组容量扩容
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

    // 最大容量：近似等于Integer.MAX_VALUE
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }


    // 数组的元素个数
    public synchronized int size() {
        return size;
    }

    // 是否为空
    public synchronized boolean isEmpty() {
        return size == 0;
    }

    // 指定位置添加元素
    private synchronized void insertElementAt(E obj, int index) {
        modCount++;
        if (index > size) {
            throw new ArrayIndexOutOfBoundsException(index
                                                     + " > " + size);
        }
        ensureCapacityHelper(size + 1);
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = obj;
        size++;
    }

    // 移除指定元素
    private synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }
    // 移除指定位置上的元素
    private synchronized void removeElementAt(int index) {
        modCount++;
        if (index >= size) {
            throw new ArrayIndexOutOfBoundsException(index + " >= " +
                    size);
        }
        else if (index < 0) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        int j = size - index - 1;
        if (j > 0) {
            System.arraycopy(elementData, index + 1, elementData, index, j);
        }
        size--;
        elementData[size] = null; /* to let gc do its work */
    }
    @SuppressWarnings("unchecked")
    E elementData(int index) {
        return (E) elementData[index];
    }

    @Override
    public synchronized void forEach(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        @SuppressWarnings("unchecked")
        final E[] elementData = (E[]) this.elementData;
        final int elementCount = this.size;
        for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
            action.accept(elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
    }

}
